package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoradService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService; // service引用注解的时候,注意不要出现循环引用,A引用B , B引用A
    @Resource
    private IBoradService boradService;

    /**
     * 创建新发布的帖子
     * @param article 要发布的帖子
     */
    @Transactional // 当前方法的执行过程会被事务管理起来
    @Override
    public void create(Article article) {
        // 插入一篇文章
        if (article == null || article.getUserId() == null
        || article.getBoardId() == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 判断文章内容
        if (StringUtil.isEmpty(article.getTitle()) || StringUtil.isEmpty(article.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 插入文章
        int row = articleMapper.insertSelective(article);
        if (row <= 0) {
            log.warn(ResultCode.FAILED.toString() + "实际影响行数" + row);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 修改用户的文章数量 这里需不需要获取用户对象,再根据对象修改 用户如果不存在的话?
        userService.addOneArticleCountById(article.getUserId());
        // 修改板块的文章数量
        boradService.addOneArticleCountById(article.getBoardId());

        log.info(ResultCode.SUCCESS.toString() + "发帖成功"+ "articleid" + article.getId());

    }

    @Override
    public List<Article> selectAll () {
        List<Article> results = articleMapper.selectAll();
        return results;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        if (boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Board board = boradService.selectById(boardId);
        if (board == null) {
            // 该版块不存在
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return  articles;
    }

    /**
     * 根据文章id查询文章
     * @param id 文章id
     * @return
     */
    @Override
    public Article selectByPrimaryKey(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    /**
     * 根据文章id查询文章
     * @param id 文章id
     * @return
     */
    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public Article selectDetailById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() +1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row <= 0) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        article.setVisitCount(article.getVisitCount() + 1);
        return article;

    }

    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || id <= 0 || StringUtil.isEmpty(title) ||
        StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        HttpSession session = request.getSession(false);
//        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
//        Article article = selectByPrimaryKey(id);
//        if (user.getId() != article.getUserId()) {
//            // 不是文章作者 , 无权修改
//            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
//        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 点赞
     * @param id
     */
    @Override
    public void thumbsUpById(Long id) {
        // 判断id
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取查询文章
        Article article = articleMapper.selectByPrimaryKey(id);
        // 判断文章是否存在
        if (article == null || article.getState() == 1 || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        // 构造更新文章
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setUpdateTime(new Date());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 操作成功了
    }

    /**
     * 根据帖子id删除文章
     * @param id 帖⼦Id
     */
    @Override
    public void deleteById(Long id) {
        // 判断id
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取查询文章
        Article article = articleMapper.selectByPrimaryKey(id);
        // 判断文章是否存在
        if (article == null ||  article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte)1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 对用户发表的帖子数-1
        userService.subOneArticleCountById(article.getUserId());
        // 版块帖子数-1
        boradService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖⼦成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");

    }

    /**
     * 文章回复数减1
     * @param id
     */
    @Override
    public void addOneReplyCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取查询文章
        Article article = articleMapper.selectByPrimaryKey(id);
        // 判断文章是否存在
        if (article == null ||  article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            // 文章状态异常
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString() + "文章状态异常");
            throw new ApplicationException(AppResult.failed("文章状态异常"));
        }

        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }


    }

    public List<Article> selectByUserId(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);
        if (user == null ) {
            log.warn(ResultCode.FAILED_USER_NOTEXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOTEXISTS));
        }
//        如果用户状态异常,但是用户所发布的文章是可以查看的吧
        List<Article> result = articleMapper.selectByUserId(userId);
        if (result == null) {
            result = new ArrayList<>();
        }
        return result;
    }


}
